<?php
/**
 * User: xuhong
 * Date: 2018/10/30
 */

namespace extend\wechat\mini;

class Encrypt
{
    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;


    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $appid string 加密的用户数据
     * @param $sessionKey string 加密的用户数据
     * @param $encryptedData string 加密的用户数据
     * @param $encryptedKey string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public static function decrypt($appid, $encryptedData, $encryptedKey, $sessionKey, &$data)
    {
        if (strlen($sessionKey) != 24) {
//            return self::$IllegalAesKey;
            return "sessionKey值格式错误";
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($encryptedKey) != 24) {
//            return self::$IllegalIv;
            return "encryptedKey值格式错误";
        }
        $aesIV = base64_decode($encryptedKey);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
//            return self::$IllegalBuffer;
            return "解码失败";
        }
        if ($dataObj->watermark->appid != $appid) {
//            return self::$IllegalBuffer;
            return "解码小程序appid不对应";
        }
        $data = $result;
        return 0;
    }
}